use std::mem::MaybeUninit;
use std::net::{SocketAddr, TcpListener};
use socket2::{Socket, Domain, Type, Protocol};
use std::io::{self, Read};
use std::thread;
use std::time::Duration;
fn main() -> io::Result<()> {
    thread::spawn(|| {
        let address: SocketAddr = "10.129.207.185:8034".parse().unwrap();
        // println!("Connecting to {}", address);
        let address = address.into();

        match Socket::new(Domain::IPV4, Type::RAW, None) {
            Ok(mut socket) => {
                if let Err(e) = socket.bind(&address) {
                    println!("Failed to bind: {}", e);
                }
                // socket.bind(&address).unwrap();
                println!("Socket created and bound to {}", address.as_socket_ipv4().unwrap());
                let mut buffer = [0; 512];
                match socket.read(&mut buffer[..]) {
                    Ok(size) => {
                        println!("Received: {:?}", &buffer[..size]);
                    },
                    Err(e) => println!("Failed to receive data: {}", e)
                };
            },
            Err(e) => println!("Failed to create socket: {}", e)
        }

    });

    let mut addresses = lookup::get_addrs().unwrap();

    addresses.des_ip_addr = [60,204,241,149];

    let mut buffer = String::new();
    loop {
        buffer.clear();
        std::io::stdin().read_line(&mut buffer).unwrap();
        if buffer.trim() == "exit" {
            break;
        }
        match lookup::send_tcp_syn(8034, &addresses, 10, 0) {
            Ok(mut cap) => {
                println!("Packet sent");
                // if let Err(_) = cap.filter("port 8034", false) {
                //     println!("Failed to set filter");
                // }
                // open savefile using the capture
                // let mut savefile = cap.savefile("test.pcap").unwrap();

                // // get a packet from the interface
                // let p = cap.next_packet().unwrap();

                // // print the packet out
                // println!("packet received on network: {:?}", p);

                // // write the packet to the savefile
                // savefile.write(&p);
            }
            Err(e) => println!("Failed to send packet: {}", e),
        };
    }

    Ok(())
}
